<template>
  <div>
    <slot name="searchBar" :condition="condition" :viewoptionArr="viewoptionArr"
      :handleClickViewOption="handleClickViewOption" :hanldeClickFilter="hanldeClickFilter"
      :handleClickSearch="handleClickSearch" :handleInputSearch="handleInputSearch" :placeholder="placeholder"></slot>
    <!-- <SearchBar :keyword="condition" :viewoptionArr="viewoptionArr" @handleClickViewOption="handleClickViewOption" @hanldeClickFilter="hanldeClickFilter" @handleClickSearch="handleClickSearch" @handleInputSearch="handleInputSearch"></SearchBar> -->

    <van-popup v-model:show="isShowFilter" position="right" :style="{ height: '100%', width: '90%' }">
      <Filter @back="hanldeClickFilter" @handleClickFilterFind="handleClickFilterFind" :object="route.query.idobject">
      </Filter>
    </van-popup>

    <van-popup v-model:show="isShowViewOptions" position="top" :style="{ height: 'auto', width: '100%' }">
      <van-row class="L-viewoption-row" :class="viewoption === item[0] ? 'on' : ''"
        @click="handleSelectViewOption(item)" type="flex" align="center" justify="space-between"
        v-for="(item, index) in viewoptionArr" :key="index">
        <van-col>{{ item[1] }}</van-col>
        <van-col> <van-icon name="success" v-if="viewoption === item[0]" /></van-col>
      </van-row>
    </van-popup>

    <van-list  v-model:loading="isLoading" :finished="finished" finished-text="没有更多了" @load="onLoad">
      <!-- <div class="L-box" v-for="(item,index) in list" :key="index"> -->
      <div v-for="(item, index) in list" :key="item.id">
        <slot name="listItem" :itemData="item"></slot>
      </div>
    </van-list>

    <van-floating-bubble icon="plus" axis="xy" magnetic="x" v-model:offset="offset" @click="handleClickAdd" />

    <van-action-sheet v-model:show="isShowSdAction" :actions="sdActions" cancel-text="取消" close-on-click-action
      @cancel="isShowSdAction = false" @select="handleSdSelect" />
  </div>

</template>

<script setup lang="ts">
import { useRouter, useRoute } from "vue-router";
const router = useRouter();
const route = useRoute();

import { onMounted, ref, watch, onActivated, defineExpose, computed, } from "vue";
defineExpose({ onLoad, initCondition });
import { apiConfigurable } from "@/request/api/api";
import { closeToast, showLoadingToast } from "vant";
import SearchBar from "@/components/common/SearchBar.vue";
import Filter from "@/components/common/Filter.vue";

import { useCheck } from "@/hooks/hooks.js";
const { checkCustomized } = useCheck();

import { useRouterStore } from "@/stores/router";
const routerStore = useRouterStore();

onMounted(() => { });

const offset = ref({ x: -20, y: 440 });

const list = ref([]);
const startline = ref(1);
const pagecount = ref(10); //每页条数
const firstLoad = ref(true); //是否第一次加载
const isLoading = ref(false); //是否加载中
const finished = ref(false); //列表是否加载完成
const placeholder = ref("请输入")

const sortType = ref(""); //排序方式
const sortBy = ref(""); //排序字段

const extract = ref(route.query.extract);
const searchedtags = ref([]);

const viewoptionArr = ref([]); //视图选项数组
const viewoption = ref(""); //当前视图
watch(viewoption, (newv,oldv) => {
  console.log(newv,'qqqqq',oldv)
  if (newv == oldv) return
  startline.value = 1;
  finished.value = false;
  list.value = [];
  isShowViewOptions.value = false
  onLoad();
})

const condition = ref(""); //搜索关键字

function handleClickSearch(value: string) {
  condition.value = value;
  initCondition();
  onLoad();
}

function handleInputSearch(value: string) {
  condition.value = value;
}

//初始化查询条件
function initCondition() {
  startline.value = 1;
  finished.value = false;
  list.value = [];

  conditiondata.value = [];
  sortBy.value = "";
  sortType.value = "asc";
  searchedtags.value = [];
  // viewoption.value = "";
  placeholder.value = "请输入"
}

//显示视图条件
const isShowViewOptions = ref(false);
function handleClickViewOption(value: boolean) {
  isShowViewOptions.value = value;
}
function handleSelectViewOption(item) {
  viewoption.value = item[0]
  isShowViewOptions.value = false

}

// watch(viewoption, (val) => {
//   isShowViewOptions.value = false;
//   initCondition();
//   onLoad();
// });

//显示过滤层
const isShowFilter = ref(false);
const conditiondata = ref([]);
function hanldeClickFilter(value: boolean) {
  isShowFilter.value = value;
}

function handleClickFilterFind(filterObj) {
  initCondition();
  conditiondata.value = filterObj.fieldArr;
  sortBy.value = filterObj.sortBy;
  sortType.value = filterObj.sortType;
  searchedtags.value = filterObj.selectedTags;
  isShowFilter.value = false;
  onLoad();
}

interface tags {
  [id: string]: boolean;
}
interface data {
  [key: string]: any;
}

const props = defineProps({
  filterapi: {
    type: String,
    default: "",
  },
  loadapi: {
    type: String,
    default: "",
  },
});

const sdlist = ref([]);

function onLoad() {
  const { idobject, idtemplate, stitle, extract } = route.query;
  const tags: tags = {};
  searchedtags.value.forEach((item) => {
    tags[item] = true;
  });

  let data: data = {
    startline: startline.value,
    pagecount: pagecount.value,
    condition: condition.value,
    orderby: sortBy.value,
    ascdesc: sortType.value,
    viewoption: viewoption.value,
    extract: extract,
    tags: JSON.stringify(tags),
  };

  for (let i = 0; i < conditiondata.value.length; i++) {
    data[i + "_viewcondition_field"] = conditiondata.value[i].viewcondition_field;
    data[i + "_viewcondition_relfield"] = conditiondata.value[i].viewcondition_relfield;
    data[i + "_viewcondition_value"] = conditiondata.value[i].viewcondition_value;
    data[i + "_viewcondition_comparison"] = conditiondata.value[i].viewcondition_comparison;
    data[i + "_viewcondition_object"] = conditiondata.value[i].viewcondition_object;
    data[i + "_viewcondition_uitype"] = conditiondata.value[i].viewcondition_uitype;
  }

  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
    duration: 0,
  });

  isLoading.value = true;

  const loadapi = `${idobject as string}.list.do`;

  apiConfigurable(loadapi, data).then((res) => {
    if (res.data?.jsondata?.fieldValue.length < pagecount.value) {
      finished.value = true;
    }
    list.value = [...list.value, ...res.data?.jsondata?.fieldValue];

    sdlist.value = res.data.sdlist || [];

    startline.value = list.value.length + 1;

    // if (firstLoad.value) {
    viewoptionArr.value = res.data?.viewOptions || [];
    if (!viewoption.value) {
      if (viewoptionArr.value.filter(item => item[2] === '1')[0]) {
        viewoption.value = viewoptionArr.value.filter(item => item[2] === '1')[0][0];
      }
    }



    if (res.data?.viewcondition?.length > 0) {
      placeholder.value = res.data?.viewcondition.reduce((pre, item, index) => {
        return `${pre}${index === 0 ? '' : '/'}${item.viewcondition_title}`
      }, "请输入")
    }
    // console.log("viewoption",viewoption.value)


    firstLoad.value = false;
    // }
    closeToast();
    isLoading.value = false;
  });
}

function handleClickAdd() {
  if (sdlist.value.length > 0) {
    isShowSdAction.value = true;
  } else {
    const { idobject, idtemplate, stitle } = route.query;
    const path = checkCustomized(`/${idobject}Form`)
      ? `/${idobject}Form`
      : "/defaultForm";

    router.push({
      path,
      query: { idobject, idtemplate, stitle },
    });
  }
}

interface sdItemIF {
  refob: string;
  refobs: string;
  sdidview: string;
  sdrelopeid: string;
  sdsubviewid: string;
  sdtitle: string;
  sdtype: string;
  name?: string;
}

const isShowSdAction = ref(false);
const sdActions = computed(() => {
  const addItem = {
    refob: "",
    refobs: "",
    sdidview: "",
    sdrelopeid: "",
    sdsubviewid: "",
    sdtitle: "",
    sdtype: "",
    name: "新建",
  };
  return [
    ...sdlist.value.map((item: sdItemIF) => {
      return { name: item.sdtitle, ...item };
    }),
    addItem,
  ];
});

function handleSdSelect(selectItem: sdItemIF) {
  if (selectItem.name == "新建") {
    const { idobject, idtemplate, stitle } = route.query;
    const path = checkCustomized(`/${idobject}`)
      ? `/${idobject}Form`
      : "/defaultForm";

    router.push({
      path,
      query: { idobject, idtemplate, stitle },
    });
    return;
  }
  const query = {
    idobject: route.query.idobject,
    sdtype: selectItem.sdtype,
    viewid: selectItem.sdidview,
    subviewid: selectItem.sdsubviewid,
    relopeid: selectItem.sdrelopeid,
    refobject: selectItem.refob,
    subrefobject: selectItem.refobs,
  };
  router.push({
    path: "/sd",
    query,
  });
}

onActivated(() => {
  if (routerStore.mode === "reload") {
    initCondition();
    onLoad();
    routerStore.mode = "";
  }
});
</script>

<style scoped>
.L-viewoption-row {
  padding: 10px;
}

.L-viewoption-row:active {
  background: #f9f9f9;
}

.on {
  color: #1683f7;
}
</style>